//
//  Lookup.m
//  Words2
//
//  Created by Mathieu Tozer on 22/09/06.
//  Copyright 2006 __MyCompanyName__. All rights reserved.
//

#import "Lookup.h"
#import "DictionaryMO.h"
#import "WordMO.h"
#import "Blob.h"


@implementation Lookup

+ (void)connectWithPorts:(NSArray *)portArray
{
    NSAutoreleasePool *pool;
    NSConnection *serverConnection;
    Lookup *serverObject;
	
    pool = [[NSAutoreleasePool alloc] init];
	
    serverConnection = [NSConnection
            connectionWithReceivePort:[portArray objectAtIndex:0]
							 sendPort:[portArray objectAtIndex:1]];
	
    serverObject = [[self alloc] init];
    [(id)[serverConnection rootProxy] setServer:serverObject];
    [serverObject release];
	
    [[NSRunLoop currentRunLoop] run];
    [pool release];
	
    return;
}

//given the words and the dictionaries, attempt to get all the definitions you can! 
//assume that the given dictionaries are connected and can be queried for words at will, but we'll double check anyway
//Pop any definitionBlobs into the appropriate blob.

-(void)defineWords:(NSArray *)words inDictionaries:(NSArray *)dictionaries{
	NSMutableDictionary *dashboard = nil;
	NSEnumerator *dictEnum = [dictionaries objectEnumerator];
	WordMO *word;
	DictionaryMO* dict;
	NSString *capabilityKey;
	NSMutableString *definitionsBlob;
	while(dict = [dictEnum nextObject]){
		if([dict isAvailable]){
			[dict connect]; //this is the actual connection to really remote dictionaries!
			NSEnumerator *wordEnum = [words objectEnumerator];
			capabilityKey = [dict valueForKey:@"targetLanguages"]; 
			NSLog(@"Looking up %@ definitions in %@", capabilityKey, [dict valueForKey:@"name"]); //report what we're doing
			
			while(word = [wordEnum nextObject]){
				NSLog(@"---- %@", [word valueForKey:@"word"]);
				if (![word isDefined]){ //if the next word is not defined already
					definitionsBlob = [dict stringBlobOfDefinitions:[word valueForKey:@"word"]]; //get a string blob of definitions the next word in the current dictionary;				
					if(definitionsBlob != nil){ //provided we have a definition to speak of
						dashboard = [[[NSMutableDictionary alloc] init] retain];
						NSAttributedString *attributedDef = [[[NSAttributedString alloc] initWithString:definitionsBlob] autorelease]; 
						[dashboard setValue:attributedDef forKey:[[[dict objectID] URIRepresentation] absoluteString]];
					} else{ NSLog(@"Nothing Found!"); }
				} else { NSLog(@"(Already Defined)"); }
				//package up this words dashboard and send it on it's way back to the main thread
				if(dashboard){		
					NSData *dashboardData = [NSKeyedArchiver archivedDataWithRootObject:dashboard];
					[word setValue:dashboardData forKey:@"dashboardData"];
					[dashboard release]; dashboard = nil;
				}
			}
		}else{ NSLog(@"Dictionary %@ Not Available. Did it become unavailable along the way somewhere?", [dict valueForKey:@"name"]); }
	}
	//clean up
	[[NSApp delegate] stopDefiningAllWordsAnimation];
}

// connect to the dictionaries in dict array
-(void)connectToDictionaries:(NSArray *)dicts{
	NSEnumerator *connectDictEnum = [dicts objectEnumerator];
	DictionaryMO *connectDict; 
	while(connectDict = [connectDictEnum nextObject]){ // get the next dictionary
		if([connectDict networkConnectionMonitor] == nil){ //if it doesn't have a connection monitor
			[connectDict createConnectionMonitor];	// create one 
		}
	}
}

//returns the definition object for the current word for the capability key, nil otherwise
//- (DefinitionMO *)definitionForWord:(WordMO *)word forCapabilityKey:(NSString *)key{
//	//get the defs associated to this word
//	NSSet *defSet = [word mutableSetValueForKey:@"definitions"];
//	if([defSet count] == 0){
//		return nil; //that's it, we're done
//	}
//	//otherwise we have to fish out the approrite one
//	NSMutableArray *array = [NSMutableArray arrayWithArray:[defSet allObjects]];
//	
//	NSEnumerator *e = [array objectEnumerator];
//	DefinitionMO *nextDef; 
//	while(nextDef = [e nextObject]){
//		if([[nextDef valueForKey:@"capabilityKey"] isEqualToString:key]){
//			return nextDef;
//		}
//	}
//	return nil;
//}
@end
